package app.hzvmap.com.rangecontrol.views;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.Map;

public class X5ProgressWebView extends WebView {

    private Context context;
    private ProgressBar bar;

    public OnWebViewCallback callback;

    public X5ProgressWebView(Context context) {
        super(context);
        init(context);
    }

    public X5ProgressWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init(context);
    }

    public X5ProgressWebView(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        init(context);
    }

    public X5ProgressWebView(Context context, AttributeSet attributeSet, int i, boolean b) {
        super(context, attributeSet, i, b);
        init(context);
    }

    public X5ProgressWebView(Context context, AttributeSet attributeSet, int i, Map<String, Object> map, boolean b) {
        super(context, attributeSet, i, map, b);
        init(context);
    }

    private void init(final Context context) {
        this.context = context;
        setUserAgent("MQQBrowser_Android_" + context.getPackageName());
        bar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        bar.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 6));
        bar.setProgressDrawable(new ColorDrawable(Color.GREEN));
        addView(bar);
        setVerticalScrollBarEnabled(false);
        WebSettings webSetting = this.getSettings();
        webSetting.setAllowContentAccess(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setSavePassword(true);
        webSetting.setSaveFormData(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setAllowFileAccessFromFileURLs(true);
        webSetting.setAllowUniversalAccessFromFileURLs(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setLoadsImagesAutomatically(true);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(context.getCacheDir().getAbsolutePath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setDefaultFontSize(14);        // 默认文字尺寸，默认值16，取值范围1-72
        webSetting.setDefaultFixedFontSize(14);   // 默认等宽字体尺寸，默认值16
        webSetting.setMinimumFontSize(10);         // 最小文字尺寸，默认值 8
        webSetting.setMinimumLogicalFontSize(10);  // 最小文字逻辑尺寸，默认值 8
        webSetting.setTextZoom(100);              // 文字缩放百分比，默认值 100
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //两者都可以
            webSetting.setMixedContentMode(webSetting.getMixedContentMode());
        }
        setWebContentsDebuggingEnabled(true);
        setWebChromeClient(new X5WebChromeClient());
        setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("urlLoading", url);
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    context.startActivity(intent);
                    return true;
                } else {
                    return false;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (callback != null) {
                    callback.onLoadCallback(url,1);
                }
            }

            @Override
            public void onPageStarted(WebView webView, String url, Bitmap bitmap) {
                super.onPageStarted(webView, url, bitmap);
                if (callback != null) {
                    callback.onLoadCallback(url,0);
                }
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                callback.onReceivedError();
            }
        });
        CookieSyncManager.createInstance(context);
        CookieSyncManager.getInstance().sync();
    }

    public void setCallback(OnWebViewCallback callback) {
        this.callback = callback;
    }

    public void setProgressDrawable(int color) {
        bar.setProgressDrawable(new ColorDrawable(color));
    }

    public void setUserAgent(String ua) {
        getSettings().setUserAgentString(ua);
    }

    private class X5WebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

            AlertDialog.Builder b2 = new AlertDialog.Builder(getContext())
                    .setTitle("提示").setMessage(message)
                    .setPositiveButton("确定",
                            new AlertDialog.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    result.confirm();
                                }
                            });

            b2.setCancelable(false);
            b2.create();
            b2.show();
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                bar.setVisibility(GONE);
            } else {
                if (bar.getVisibility() == GONE) {
                    bar.setVisibility(VISIBLE);
                }
                bar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (callback != null) {
                callback.onReceivedTitle(title);
            }
        }



        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            if (callback != null) {
                callback.openFileChooser(uploadMsg);
            }
        }

        // For Android > 4.1.1
        @Override
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            openFileChooser(uploadMsg, "");
        }

        // For Android  >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, FileChooserParams fileChooserParams) {
            if (callback != null) {
                callback.onShowFileChooser(uploadMsg);
            }
            return true;
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        ViewGroup.LayoutParams lp = bar.getLayoutParams();
        lp.width = l;
        lp.height = t;
        bar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }

    public interface OnWebViewCallback {

        void onUrlCallback(String url);

        void onLoadCallback(String url, int status);

        void openFileChooser(ValueCallback<Uri> uploadMsg);

        void onShowFileChooser(ValueCallback<Uri[]> uploadMsg);

        void onReceivedTitle(String title);

        void onReceivedError();
    }

}
